<template>
  <el-row :gutter="16">
    <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
      <div class="chart-card card">
        <div class="header">
          <ul class="tab">
            <li
              v-for="(value, key) in chart.tabsData"
              :key="key"
              :class="chart.curTab == key ? 'active' : ''"
              @click="onChangeCurTab(key)"
            >
              {{ value }}
            </li>
          </ul>

          <span class="time">
            <el-date-picker
              v-model="chart.dateTime"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="chart.shortcuts"
              @change="onChangeDateTime"
              :editable="false"
            >
            </el-date-picker>
          </span>
        </div>

        <div class="container">
          <v-chart v-if="chart.dateTime" :option="chartOption" autoresize />
          <sa-empty v-if="!chart.dateTime"></sa-empty>
        </div>
      </div>
    </el-col>
    <el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
      <el-row :gutter="16">
        <el-col
          v-for="(value, key) in statistics"
          :key="key"
          :xs="12"
          :sm="12"
          :md="12"
          :lg="12"
          :xl="12"
        >
          <card :type="key" :data="value" :dateTime="chart.dateTime" />
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script setup>
  import { onMounted, reactive } from 'vue';
  import VChart from 'vue-echarts';
  import dayjs from 'dayjs';
  import { api } from '../../outline.service';
  import Card from './card.vue';

  const props = defineProps(['data']);

  const chart = reactive({
    tabsData: {
      order: '订单数',
      payOrder: '支付订单',
      payAmount: '支付金额',
    },
    curTab: 'order',
    dateTime: getTimeSlot(),
    shortcuts: [
      {
        text: '今天',
        value: getTimeSlot(),
      },
      {
        text: '昨天',
        value: () => {
          return getTimeSlot('yesterday');
        },
      },
      {
        text: '近一周',
        value: () => {
          return getTimeSlot('week');
        },
      },
    ],
    data: {
      payAmountArr: [], // 销售额
      payOrderArr: [], // 订单
      orderArr: [], //订单数
    },
  });

  function onChangeCurTab(type) {
    chart.curTab = type;
    chartOption.series[0].name = chart.tabsData[chart.curTab];
    initChart();
  }

  function onChangeDateTime(e) {
    // 时间date必选
    e && getChart();
  }

  const statistics = reactive({
    order: {
      num: 0,
      text: '订单数',
      path: '',
      tip: '时间区间内总的下单数量(包含未支付订单)',
      status: 'all',
    },
    payAmount: {
      num: 0,
      text: '支付金额',
      path: '',
      tip: '时间区间内支付订单的支付总金额(包含退款订单)',
      status: 'paid',
    },
    payOrder: {
      num: 0,
      text: '支付订单',
      path: '',
      tip: '时间区间内支付的订单数量(包含退款订单)',
      status: 'paid',
    },
    noSend: {
      num: 0,
      text: '待发货订单',
      path: '',
      tip: '时间区间内待发货订单数量',
      status: 'nosend',
    },
    aftersale: {
      num: 0,
      text: '售后维权',
      path: '',
      tip: '时间区间内申请售后维权的订单数量',
      status: 'aftersale',
    },
    refund: {
      num: 0,
      text: '退款订单',
      path: '',
      tip: '时间区间内退款的订单数量',
      status: 'refund',
    },
  });

  async function getChart() {
    const { error, data } = await api.chart({
      date: chart.dateTime.join(' - '),
    });
    if (error === 0) {
      for (let key in statistics) {
        statistics[key].num = data[`${key}Num`];
      }

      chart.data.payAmountArr = data.payAmountArr; // 销售额
      chart.data.payOrderArr = data.payOrderArr; // 订单
      chart.data.orderArr = data.orderArr; //订单数

      initChart();
    }
  }

  // 柱状图参数
  const chartOption = reactive({
    grid: {
      left: '10px',
      top: '20px',
      bottom: '20px',
      right: '20px',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: [],
      offset: 5,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      offset: 5,
      splitLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        show: true,
        status: 'shadow',
        z: -1,
        shadowStyle: {
          color: 'rgba(191, 191, 191, 0.24)',
        },
        type: 'shadow',
      },
    },
    series: [
      {
        name: chart.tabsData[chart.curTab],
        type: 'bar',
        data: [],
        zlevel: 1,
        z: 1,
        label: {
          show: false,
          position: 'top',
        },
        itemStyle: {
          color: '#806af6',
        },
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(191, 191, 191, 0.24)',
        },
      },
    ],
  });

  // 获取时间刻度
  function initChart() {
    if (chart.dateTime) {
      let time =
        (new Date(chart.dateTime[1].replace(/-/g, '/')).getTime() -
          new Date(chart.dateTime[0].replace(/-/g, '/')).getTime()) /
        1000 +
        1;
      let kld = '';
      let interval = 0;
      if (time <= 60 * 60) {
        interval = parseInt(time / 60);

        kld = 'minutes';
      } else if (time <= 60 * 60 * 24) {
        interval = parseInt(time / (60 * 60));

        kld = 'hours';
      } else if (time <= 60 * 60 * 24 * 30 * 1.5) {
        interval = parseInt(time / (60 * 60 * 24));

        kld = 'days';
      } else if (time < 60 * 60 * 24 * 30 * 24) {
        interval = parseInt(time / (60 * 60 * 24 * 30));

        kld = 'months';
      } else if (time >= 60 * 60 * 24 * 30 * 24) {
        interval = parseInt(time / (60 * 60 * 24 * 30 * 12));

        kld = 'years';
      }
      drawX(interval, kld);
    } else {
      chartOption.xAxis.data = [];
      chartOption.series[0].data = [];
    }
  }
  // 给柱状图数据赋值
  function drawX(interval, kld) {
    let x = [];
    let y = [];
    let timeStamp = [];
    for (let i = 0; i <= interval - 1; i++) {
      if (kld == 'minutes' || kld == 'hours') {
        x.push(dayjs(chart.dateTime[0]).add(i, kld).format('DD HH:mm'));
        y.push(0);
      } else if (kld == 'days') {
        x.push(dayjs(chart.dateTime[0]).add(i, kld).format('YYYY-MM-DD'));
        y.push(0);
      } else if (kld == 'months') {
        x.push(dayjs(chart.dateTime[0]).add(i, kld).format('YYYY-MM'));
        y.push(0);
      } else {
        x.push(dayjs(chart.dateTime[0]).add(i, kld).format('YYYY'));
        y.push(0);
      }
    }
    for (let i = 1; i <= interval; i++) {
      timeStamp.push(dayjs(chart.dateTime[0]).add(i, kld).valueOf());
    }
    x.forEach((item, index) => {
      chart.data[`${chart.curTab}Arr`].forEach((item) => {
        if (
          item.create_time > (index - 1 >= 0 ? timeStamp[index - 1] : 0) &&
          item.create_time <= timeStamp[index]
        ) {
          if (chart.curTab == 'payAmount') {
            y[index] = (Number(y[index]) + Number(item.counter)).toFixed(2);
          } else {
            y[index]++;
          }
        }
      });
    });
    chartOption.xAxis.data = x;
    chartOption.series[0].data = y;
  }
  // 默认获取当天的时间赋值
  function getTimeSlot(e) {
    let beginTime = dayjs(new Date()).format('YYYY-MM-DD');
    let endTime = dayjs(new Date()).format('YYYY-MM-DD');
    switch (e) {
      case 'yesterday':
        endTime = dayjs().subtract(1, 'days').format('YYYY-MM-DD');
        beginTime = endTime;
        break;
      case 'week':
        beginTime = dayjs().subtract(1, 'weeks').format('YYYY-MM-DD');
        break;
      case 'month':
        beginTime = dayjs().subtract(1, 'months').format('YYYY-MM-DD');
    }
    let timeSlot = [beginTime + ' 00:00:00', endTime + ' 23:59:59'];
    return timeSlot;
  }

  onMounted(() => {
    getChart();
  });
</script>

<style lang="scss" scoped>
  .chart-card {
    padding: 12px var(--sa-padding) 0 !important;
    min-height: 355px;
    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
      flex-wrap: wrap;
      ul {
        li {
          list-style: none;
          float: left;
          margin-right: 24px;
          font-size: 14px;
          height: 32px;
          line-height: 32px;
          color: var(--sa-subfont);
          cursor: pointer;
          &.active {
            color: var(--sa-subtitle);
            font-weight: bold;
          }
        }
      }
      .time {
        @media only screen and (max-width: 768px) {
          :deep() {
            .el-date-editor {
              --el-date-editor-datetimerange-width: 320px;
            }
          }
        }
      }
    }
    .container {
      height: 295px;
      .echarts {
        height: 100%;
        width: 100%;
      }
    }
  }
</style>
